<template>
  <div class="file-list tech-card">
    <div class="file-list-header">
      <div>
        <h3 class="neon-title-small">{{ title }} <span class="sub-text">// DOCUMENT LOG</span></h3>
        <p class="sub-text">最近访问 · {{ files.length }} 个文件</p>
      </div>
      <div class="btn-group">
        <el-upload class="upload-demo" action="/api/knowledge/upload" :file-list="fileList"
          :data="{ knowledgeCode: knowledgeCode }" :before-upload="beforeUpload" :on-success="handleSuccess"
          :on-error="handleError" :show-file-list="false" :limit="1" :on-exceed="handleExceed" multiple auto-upload
          list-type="text">
          <el-button type="primary" size="small" class="tech-button primary-btn">
            <i class="el-icon-upload2"></i> 📤 选择并上传文件
          </el-button>
        </el-upload>
      </div>
    </div>

    <el-table :data="files" border stripe class="tech-table">
      <el-table-column label="文件名" min-width="250">
        <template slot-scope="scope">
          <i :class="getFileIcon(scope.row.fileType)" class="tech-icon-small"></i>
          <span class="file-name-text">{{ scope.row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" width="100" prop="fileType" />
      <el-table-column label="上传时间" width="180" prop="createTime" class="monospace-text"/>
      <el-table-column label="修改时间" width="180" prop="updateTime" class="monospace-text"/>
      <el-table-column label="大小" width="100" prop="fileSizeStr" class="monospace-text"/>

      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :class="scope.row.statusType === '已处理' ? 'tech-tag-success' : 'tech-tag-warning'" disable-transitions>
            {{ scope.row.statusType }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-view" class="tech-text-btn"
            @click="$file.handleKnowledgeFileNameClick(scope.row)"></el-button>
          <el-button type="text" icon="el-icon-delete" class="tech-text-btn delete-btn"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="view-more">
      <el-link class="tech-link" @click="handleViewMore">查看全部文件 >></el-link>
    </div>
  </div>
</template>

<script>
// JavaScript 逻辑保持不变
export default {
  name: 'FileList',
  props: {
    title: {
      type: String,
      default: '业务文档库'
    },
    files: {
      type: Array,
      required: true
    },
    knowledgeCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      allowedTypes: [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain',
      ],
      loadingInstance: null,
    }
  },
  methods: {
    beforeUpload(file) {
      const isAllowed = this.allowedTypes.includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isAllowed) {
        this.$message.error('❌ 仅支持 PDF、Word、Excel、TXT 文档，禁止上传图片、音视频！');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('❌ 文件大小不能超过 5MB！');
        return false;
      }

      // ✅ 开启全局 loading
      this.loadingInstance = this.$loading({
        lock: true,
        text: '文件已上传，正在进行智能解析，请耐心等待约 5~10 秒…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)', // 增加背景透明度，匹配科技主题
      });
      return true;
    },
    handleSuccess(response, file) {
      this.closeLoading();
      this.$emit('dataLoadding');
      this.$message.success(`✅ "${file.name}" 上传成功`);
      this.fileList = []
    },
    handleError(err, file) {
      this.closeLoading();
      this.$message.error(`❌ "${file.name}" 上传失败`);
      this.fileList = []
    },
    handleExceed(files, fileList) {
      this.$message.warning('⚠️ 最多只能上传 1 个文件');
    },
    // 关闭 loading（确保一定会被调用）
    closeLoading() {
      if (this.loadingInstance) {
        this.loadingInstance.close();
        this.loadingInstance = null;
      }
    },
    /**
     * * @param fileType 获取文件 icon 图标
     */
    getFileIcon(fileType) {
      switch (fileType) {
        case 'pdf':
          return 'el-icon-document';
        case 'docx':
          return 'el-icon-document';
        case 'xlsx':
          return 'el-icon-s-data';
        case 'pptx':
          return 'el-icon-s-marketing';
        default:
          return 'el-icon-document';
      }
    },
    /** 文件预览 */
    handlePreview(file) {
      this.$message(`预览文件：${file.fileName}`)

      const fileSuffix = (file.extendName || '').toLowerCase()

      // 拦截图片、音频、视频类型，不处理
      const IMAGE_TYPES = ['png', 'jpg', 'jpeg', 'gif', 'svg']
      const VIDEO_TYPES = ['mp4']
      const AUDIO_TYPES = ['mp3', 'flac']

      if (
        IMAGE_TYPES.includes(fileSuffix) ||
        VIDEO_TYPES.includes(fileSuffix) ||
        AUDIO_TYPES.includes(fileSuffix)
      ) {
        this.$message.warning('该文件类型不支持预览')
        return
      }

      // Office 文件在线预览
      if ([...officeFileType].includes(fileSuffix)) {
        this.getFileOnlineViewPathByOffice(file)
        return
      }

      // PDF 文件新标签页打开
      if (fileSuffix === 'pdf') {
        window.open(this.getViewFilePath(file), '_blank')
        return
      }

      // 统一 yaml => yml
      let codeSuffix = fileSuffix === 'yaml' ? 'yml' : fileSuffix

      // Markdown 文档
      if (markdownFileType.includes(codeSuffix)) {
        Vue.prototype.$openBox.markdownPreview({
          fileInfo: file,
          editable: false
        })
        return
      }

      // 文本/代码类文件 或 无扩展名文件
      if (
        fileSuffixCodeModeMap.has(codeSuffix) ||
        (file.isDir === 0 && !file.extendName)
      ) {
        Vue.prototype.$openBox.codePreview({ fileInfo: file, isEdit: false })
        return
      }

      // 其他不支持预览
      this.$message.warning('暂不支持该类型文件预览')
    },
    /**
     * * @param file 文件删除操作
     */
    handleDelete(file) {
      this.$confirm(`确定删除 ${file.fileName} 吗？`, '删除确认')
        .then(() => {
          this.$emit('fileDelete', file);
        })
        .catch(() => { });
    },
    handleViewMore() {
      this.$message('加载更多文件...');
    }
  }
}
</script>

<style scoped lang="less">
/* ================= 赛博朋克主题变量 (继承自父组件，这里重复以便独立调试) ================= */
@bg-dark: #0f1219;
@bg-panel: rgba(26, 31, 44, 0.7);
@primary-color: #00f2ff; /* Cyber Cyan */
@accent-color: #7d2ae8;  /* Neon Purple */
@text-main: #e2e8f0; // 浅色主文本
@text-sub: #94a3b8;  // 辅助文本
@border-color: rgba(255, 255, 255, 0.08);

/* ================= 容器 (Card) 样式重写 ================= */
.file-list {
  /* 替换原有的白色背景为科技卡片风格 */
  background: @bg-panel;
  backdrop-filter: blur(10px);
  border: 1px solid @border-color;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
  color: @text-main;
  padding: 24px;
  border-radius: 8px;
  margin-top: 32px;
}

/* ================= 头部样式 ================= */
.file-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid @border-color;
}

.neon-title-small {
  color: @primary-color;
  text-shadow: 0 0 10px rgba(0, 242, 255, 0.5);
  font-size: 24px;
  font-weight: 700;
  margin: 0;

  .sub-text {
    font-size: 14px;
    color: @text-sub;
    margin-left: 10px;
    font-weight: normal;
  }
}

.sub-text {
  color: @text-sub;
  font-size: 13px;
  margin-top: 5px;
}

.tech-icon-small {
    color: @primary-color;
    text-shadow: 0 0 5px rgba(0, 242, 255, 0.3);
}

.file-name-text {
    color: @text-main;
}

.monospace-text {
    font-family: 'Consolas', monospace;
}

/* ================= 按钮 (Button) 样式重写 (与上一次相同) ================= */
.tech-button {
  border-radius: 4px;
  transition: all 0.3s;
  padding: 8px 15px;

  &.primary-btn {
    background: linear-gradient(90deg, @primary-color, @accent-color) !important;
    border: none !important;
    color: #fff !important;
    box-shadow: 0 0 10px rgba(0, 242, 255, 0.3);
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 15px rgba(0, 242, 255, 0.5);
    }
  }
}

/* ================= 表格 (el-table) 样式重写 - 重点修复行字体颜色 ================= */
.tech-table {
  border: 1px solid @border-color !important;
  border-radius: 4px;
  overflow: hidden;
  
  // 表格主体背景
  ::v-deep .el-table__body-wrapper {
    background: transparent !important;
  }
  
  // 头部样式
  ::v-deep .el-table__header-wrapper th {
    background-color: rgba(0, 0, 0, 0.3) !important;
    color: @primary-color !important;
    border-color: @border-color !important;
    font-weight: 600;
    font-size: 13px;
    text-transform: uppercase;
  }
  
  // 行背景和颜色
  ::v-deep .el-table__row, ::v-deep .el-table__row.hover-row {
    background-color: transparent !important;
    
    // ** 【修复】强制单元格内的文本颜色为浅色 **
    td .cell {
        color: @text-main !important; 
    }
    
    // 悬停效果
    &:hover {
      background-color: rgba(0, 242, 255, 0.08) !important;
    }
  }
  
  // 斑马纹/条纹
  ::v-deep .el-table__row.el-table__row--striped {
    background-color: rgba(255, 255, 255, 0.03) !important;
    
    &:hover {
      background-color: rgba(0, 242, 255, 0.08) !important;
    }
  }
  
  // 行分割线
  ::v-deep td {
    border-bottom: 1px dashed @border-color !important;
    border-right: none !important;
  }
}

/* ================= 标签 (el-tag) 样式重写 (与上一次相同) ================= */
.tech-tag-success {
  background-color: rgba(0, 242, 255, 0.15) !important;
  color: @primary-color !important;
  border-color: @primary-color !important;
  box-shadow: 0 0 5px rgba(0, 242, 255, 0.3);
}

.tech-tag-warning {
  background-color: rgba(255, 170, 0, 0.15) !important;
  color: #ffaa00 !important;
  border-color: #ffaa00 !important;
  box-shadow: 0 0 5px rgba(255, 170, 0, 0.3);
}

/* ================= 文本操作按钮 (el-button type="text") (与上一次相同) ================= */
.tech-text-btn {
  color: @accent-color !important;
  padding: 0 5px;
  
  &:hover {
    color: @primary-color !important;
    text-shadow: 0 0 8px rgba(0, 242, 255, 0.5);
  }
}

.tech-text-btn.delete-btn {
  &:hover {
    color: #ff6666 !important;
    text-shadow: 0 0 8px rgba(255, 102, 102, 0.5);
  }
}

/* ================= 查看更多链接 (el-link) (与上一次相同) ================= */
.view-more {
  margin-top: 15px;
  text-align: center;
}

.tech-link {
  color: @accent-color !important;
  font-weight: bold;
  font-size: 13px;
  
  &:hover {
    color: @primary-color !important;
    text-shadow: 0 0 8px rgba(0, 242, 255, 0.5);
  }
}
</style>